package com.situ.ssh.action;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.situ.ssh.common.ServerResponse;
import com.situ.ssh.entity.User;
import com.situ.ssh.service.IUserService;
import com.situ.ssh.util.JSONUtil;

//Action交给Spring容器来管理，Spring默认创建实例是singleton,
//但是struts2中每次创建Action都会创建一个新的Action，其实就是
//要求这个Action是多例的，所以要加@Scope("prototype"),告诉
//Spring Action的实例是多例的
@Controller
@Scope("prototype")
public class UserAction extends BaseAction<User>{
	private User user = new User();
	
	@Autowired
	private IUserService userService;
	
	public String login() {
		User loginUser = userService.login(user);
		System.out.println(loginUser);
		return "loginSuccess";
	}
	
	public String list() {
		List<User> list = userService.findAll();
		ActionContext actionContext = ActionContext.getContext();
		Map<String, Object> requestMap = actionContext.getContextMap();
		requestMap.put("list", list);
		return "list";
	}
	
	public String pageList() {
		String name = model.getName();
		if (StringUtils.isNotEmpty(name)) {
			//在DetachedCriteria封装离线查询条件
			//添加根据名字模糊查找
			detachedCriteria.add(Restrictions.like("name", "%" + name + "%"));
		}
		Integer age = model.getAge();
		if (age != null) {
			//添加过滤条件，根据年龄查找
			detachedCriteria.add(Restrictions.eq("age", age));
		}
		ServerResponse serverResponse = userService.pageList(searchCondition);
		//把ServerResponse转换成json格式
		JSONUtil.obj2Json(serverResponse);
		
		return NONE;
	}
	
}
